﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using ICSharpCode.SharpZipLib.Zip;
using ajayumi.develop.win32.Transport.AppUpgrade.Properties;
using ajayumi.develop.win32.Transport.AppUpgrade.Provider;
using ajayumi.develop.win32.Transport.WCF.Services;

namespace ajayumi.develop.win32.Transport.AppUpgrade.Controls
{
    /// <summary>
    /// UcUpdating.cs 更新文件
    /// Author   : 黄乙冬
    /// Date     : 2012-02-24
    /// </summary>
    public partial class UcUpdating : UcBase
    {
        #region Variables

        private UpgradeResultType m_UpgradeResult = UpgradeResultType.Failure;
        private AppPackageProvider m_AppProvider = null;

        #endregion

        #region Properties

        /// <summary>
        /// 更新文件所在文件夹
        /// </summary>
        public string UpgradeDir { get; set; }

        #endregion

        public UcUpdating()
        {
            InitializeComponent();
        }

        public UcUpdating(UcBase preControl)
            : base(preControl)
        {
            InitializeComponent();
        }

        protected override void InitDefaultValue()
        {
            base.InitDefaultValue();

            this.Title = "更新应用程序";
        }

        internal override UcBase Next()
        {
            return new UcFinish(this)
            {
                UpgradeResult = this.m_UpgradeResult
            };
        }

        private void AppendText<TCtrl>(TCtrl ctrl, string str) where TCtrl : TextBox
        {
            ctrl.Invoke(new Action<string>(ctrl.AppendText), new object[] { str });
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.SetButtonVisible(WizardFormButtons.Exit);

            switch (Program.UpgradeInfo.UpgradeRunMode)
            {
                case UpgradeRunMode.InstallationPackage:
                    break;
                case UpgradeRunMode.CompressionPackage:
                    break;
                case UpgradeRunMode.Normal:
                default:
                    this.m_AppProvider = new ZipProvider(this.UpgradeDir, (str) => this.AppendText<TextBox>(this.txtMsg, str));
                    this.AppendText<TextBox>(this.txtMsg, "升级操作将在程序关闭后开始……\r\n");
                    this.backgroundWorker1.RunWorkerAsync();
                    break;
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // 关闭待升级的应用程序
                Process[] processes = Process.GetProcessesByName(ArgumentSerialization.ProcessName);
                foreach (Process item in processes)
                {
                    DialogResult result = MessageBox.Show("程序正在运行，为了防止数据丢失，请做好保存工作。\r\n点击\"确定\"按钮，升级程序将强行关闭当前程序，并完成升级操作。", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                    if (result == DialogResult.OK)
                    {
                        item.Kill();
                    }
                    else
                    {
                        this.m_UpgradeResult = UpgradeResultType.Cancel;
                        return;
                    }
                    //item.WaitForExit();
                }

                bool isSuccess = this.m_AppProvider.Update();
                if (isSuccess)
                {
                    this.m_UpgradeResult = UpgradeResultType.Success;
                    ArgumentSerialization.Save();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.PerformNext();
        }


    }
}
